package com.acane.instagram.feature.me

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.feature.common.SessionManager

@Composable
fun SwitchAccountDialog(
    toLogin: () -> Unit,
    onDismissRequest: () -> Unit,
    loggedAccountList: MutableList<UserInfo>,
    toRegister: () -> Unit,
    toMain: () -> Unit,
) {

    Dialog(
        onDismissRequest = onDismissRequest,
        properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnBackPress = true, dismissOnClickOutside = true)
    ) {
        // 使用 Surface 组件并显式设置背景颜色为白色
        Surface(
            modifier = Modifier.fillMaxWidth().wrapContentHeight(),
            color = Color.White, // 设置背景颜色为白色
        ) {
            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.Start
            ) {
                // LOGO
                Row(
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.ins),
                        contentDescription = "logo",
                        modifier = Modifier.size(200.dp)
                    )
                }
                Spacer(modifier = Modifier.height(16.dp)) // 添加一些间距

                // 显示已经登录过的帐户列表
                LazyColumn {
                    items(loggedAccountList) { user ->
                        ShowLoggedAccountList(
                            userInfo = user,
                            toMain = toMain,
                            )
                        Spacer(modifier = Modifier.height(8.dp)) // 添加一些间距
                    }
                }

                Spacer(modifier = Modifier.height(16.dp)) // 添加一些间距

                // 切换账户，注册的文本按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "切换账户",
                        fontSize = 12.sp,
                        color = InstagramBlue,
                        modifier = Modifier.padding(horizontal = 16.dp).clickable {
                            //切换账户页面
                            Log.d("SwitchAccountDialog", "切换账户 clicked")
                            toLogin()
                            Log.d("SwitchAccountDialog", "调用完成")
                        }
                    )
                    Text(
                        text = "注册",
                        fontSize = 12.sp,
                        color = InstagramBlue,
                        modifier = Modifier.padding(horizontal = 16.dp)
                            .clickable {
                                toRegister()
                                //注册页面
                                Log.d("SwitchAccountDialog", "注册 clicked")
                            }
                    )
                }
            }
        }

    }
}

@Composable
fun ShowLoggedAccountList(
    userInfo: UserInfo,
    toMain: () -> Unit,
) {
    val context = LocalContext.current
    Row(
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Spacer(modifier = Modifier.size(10.dp))

        // 头像
        AsyncImage(
            model = userInfo.avatar?.let {
                val url = "${Config.ADDRESS}avatars/$it"
                Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                url
            },
            contentScale = ContentScale.Crop,
            contentDescription = "当前登录用户头像",
            modifier = Modifier
                .size(50.dp)
                .clip(CircleShape),
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )
        Spacer(modifier = Modifier.size(10.dp))
        // 账号名
        userInfo.userName?.let { Text(text = it, fontSize = 12.sp, modifier = Modifier.weight(1f)) }
        Spacer(modifier = Modifier.width(180.dp))
        // 登录按钮
        Button(
            onClick = {
                SessionManager._sessionId?.let { SessionManager.login(userInfo, it) }
                // 提示登录成功
                Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
                toMain()
            },
            colors = ButtonDefaults.buttonColors(containerColor = InstagramLightGray, contentColor = Color.Black),
            modifier = Modifier
                .height(30.dp)
                .padding(horizontal = 4.dp)
                .width(70.dp),
            shape = RoundedCornerShape(5.dp),
            elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
            contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
        ) {
            Text(text = "登录", fontSize = 12.sp, fontWeight = FontWeight.Bold)
        }
        Image(
            painter = painterResource(id = R.drawable.options_vertical),
            contentDescription = "options",
            modifier = Modifier.size(20.dp)
        )
    }
}
